package com.yishu.servlet;

import com.yishu.Dao.BookDao;
import com.yishu.Dao.MyBookDao;
import com.yishu.entity.Book;
import com.yishu.entity.MyBook;
import com.yishu.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class ShowAUserShopServlet extends HttpServlet {

    MyBookDao myBookDao = new MyBookDao();
    DBConnection dbConnection = new DBConnection();
    BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));
        try {
            List<Book> bookList = new ArrayList<>();
            List<MyBook> myBookList = new ArrayList<>();
            Connection connection = dbConnection.getCon();
            myBookList = myBookDao.showAUserShopping(userId,connection);
            dbConnection.closeCon(connection);

            if(myBookList.size() == 0) {
                req.setAttribute("result","你暂未添加任何书籍.");
                req.getRequestDispatcher("/userShop.jsp").forward(req,resp);
            }else {

                for(int i = 0; i < myBookList.size(); i++) {
                    int bookId = myBookList.get(i).getBookId();
                    bookList.add(bookDao.showABookDetail(bookId));
                }

                req.setAttribute("bookList",bookList);
                req.getRequestDispatcher("/userShop.jsp").forward(req,resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
